package com.aqie.rabbit.api.dlex;

import com.rabbitmq.client.Address;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

public class ConsumerTest {
    private static final String IP_ADDRESS = "127.0.0.1";
    private static final String VIRTUAL_HOST = "/";

    // 正常队列 交换机
    private static final String QUEUE_NAME = "normal_queue";
    private static final String EXCHANGE_NAME = "exchange_normal";
    private static final String ROUTING_KEY = "normal.#";

    // 死信队列
    private static final String QUEUE_DLX_NAME = "dlx_queue";
    private static final String EXCHANGE_DLX_NAME = "exchange_dlx";
    // 只要有消息到达任何路由key 均会绑定到队列
    private static final String ROUTING_DLX_KEY = "#";


    private static final String TYPE = "topic";
    private static final int PORT = 5672;

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        Address[] addresses = new Address[]{
                new Address(IP_ADDRESS, PORT)
        };
        // 1. 创建一个ConnectionFactory, 并进行配置
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setVirtualHost(VIRTUAL_HOST);

        // 2. 通过连接工厂创建连接
        Connection connection = connectionFactory.newConnection(addresses);

        // 3. 通过connection创建一个Channel
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, TYPE, true, false, null);

        // 4.arguments属性要设置到队列
        Map<String, Object> arguments = new HashMap<>();
        arguments.put("x-dead-letter-exchange", EXCHANGE_DLX_NAME);

        // 5. 声明（创建）一个队列 (姓名 持久化 独占(顺序消费) 队列脱离exchange自动删除)
        channel.queueDeclare(QUEUE_NAME, true, false, false, arguments);

        // 6.将交换器和队列通过路由绑定
        channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY);

        // 7.要进行死信队列的声明:
        channel.exchangeDeclare(EXCHANGE_DLX_NAME, TYPE, true, false, null);
        channel.queueDeclare(QUEUE_DLX_NAME, true, false, false, null);
        channel.queueBind(QUEUE_DLX_NAME, EXCHANGE_DLX_NAME, ROUTING_DLX_KEY);


        // 8.创建消费者
        channel.basicConsume(QUEUE_NAME, true, new DlxConsumer(channel));

        /*channel.close();
        connection.close();*/
    }
}
